﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class TreeNodeService
    {
        /// <summary>
        /// 扁平结构树形化
        /// </summary>
        /// <param name="flatNodes"></param>
        /// <returns></returns>
        public static List<Node> GetTreeNodes(List<Node> flatNodes)
        {
            List<Node> treeNodes = flatNodes.Where(x => x.Pid == null).ToList();

            foreach (var root in treeNodes)
            {
                GetChildByParent(root, flatNodes);
            }

            return treeNodes;
        }

        /// <summary>
        /// 递归，设置每个节点的子节点
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="flatNodes"></param>
        public static void GetChildByParent(Node parent, List<Node> flatNodes)
        {
            parent.Children = flatNodes.Where(x => x.Pid == parent.Id).ToList();
            foreach (var child in parent.Children)
            {
                GetChildByParent(child, flatNodes);
            }
        }


        /// <summary>
        /// 树形结构扁平化
        /// </summary>
        /// <param name="treeNodes"></param>
        /// <returns></returns>
        public static List<Node> GetFlatNodes(List<Node> treeNodes)
        {
            List<Node> flatNodes = new List<Node>();

            foreach (var node in treeNodes)
            {
                flatNodes.Add(node);

                foreach (var child in node.Children)
                {
                    child.Pid = node.Id;
                    flatNodes.Add(child);
                    GetChild(child, flatNodes);
                }
            }

            return flatNodes;
        }

        /// <summary>
        /// 递归，获得每个节点的子节点，并将其加入到总列表
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="flatNodes"></param>
        public static void GetChild(Node parent, List<Node> flatNodes)
        {
            foreach (var child in parent.Children)
            {
                child.Pid = parent.Id;
                flatNodes.Add(child);

                foreach (var item in child.Children)
                {
                    item.Pid = child.Id;
                    GetChild(item, flatNodes);
                }
            }

        }

    }
}
